package com.csap.framework.oauth2.server;

import cn.dev33.satoken.exception.SaTokenException;
import com.csap.framework.extension.result.ResultParam;
import com.csap.framework.extension.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @Author ycf
 * @Date 2021/8/23 9:38 下午
 * @Version 1.0
 */
@ControllerAdvice
@Slf4j
public class ServerExceptionHandler {

    /**
     * 内部自定义异常错误
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler({SaTokenException.class})
    public ResponseEntity<ResultParam<?>> handlerSellerException(SaTokenException e) {
        log.error("handlerSellerException:{},{}", e.getMessage(), e);
        return getResponse(ResultUtil.error(e.getType() == null ? String.valueOf(HttpStatus.UNAUTHORIZED.value()) : e.getType(), e.getMessage()), e.getHttpStatus());
    }

    /**
     * 公用响应
     *
     * @param resultParam 响应的参数
     * @param httpStatus  http状态
     * @return 结果
     */
    private ResponseEntity<ResultParam<?>> getResponse(ResultParam<?> resultParam, HttpStatus httpStatus) {
        return new ResponseEntity<>(resultParam, httpStatus);
    }
}
